//
//  ZDOrderDetailController.m
//  特种车调度
//
//  Created by 陈宇 on 15/8/22.
//
//

#import "ZDOrderDetailController.h"
#import "ZDOrderDetailCell.h"
#import "ZDWorkDetailController.h"
#import "ZDTruck.h"
#import "CAlertView.h"
#import "OrderManager.h"
#import "ZDEmptyWorkCell.h"

@interface ZDOrderDetailController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) CAlertView *alertView;
@property (nonatomic, strong) OrderManager *manager;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UIButton *addPriceButton;
@property (weak, nonatomic) IBOutlet UILabel *singleLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *orderNumberButton;
@property (weak, nonatomic) IBOutlet UILabel *orderPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
@property (weak, nonatomic) IBOutlet UILabel *cartypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *conditionLabel;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *personLabel;
@property (weak, nonatomic) IBOutlet UILabel *remarkLabel;
@property (weak, nonatomic) IBOutlet UIButton *calcleOrderButton;

- (IBAction)cancleOrderAction:(id)sender;
- (IBAction)addPriceAction:(id)sender;

- (IBAction)alertAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UITextField *alertPriceTextfield;

@end

@implementation ZDOrderDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.manager = [OrderManager new];
    self.tableView.rowHeight = 57.f;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDOrderDetailCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDEmptyWorkCell" bundle:nil] forCellReuseIdentifier:@"emptyCell"];
    //    self.remarkLabel.adjustsFontSizeToFitWidth = YES;
    
    [self getData];
}

- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(fireRrfresh) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return _timer;
}

- (void)fireRrfresh
{
    [self getData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:30]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //    self.timer.fireDate = [NSDate distantFuture];
}

- (void)getData
{
    [self showHudWithhint:kDefaultMessage];
    [self.manager getDispatcherOrderDetail:_order complete:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            ZDOrder *order = response.result;
            NSMutableArray *logs = [NSMutableArray arrayWithArray:order.orderLogs];
            NSMutableArray *gpSuccessArr = [NSMutableArray array];
            [logs enumerateObjectsUsingBlock:^(OrderLog *obj, NSUInteger idx, BOOL *stop) {
                if (obj.statusId == ZDOwnerStatusGPSuccess) {
                    [gpSuccessArr addObject:obj];
                }
            }];
            for (OrderLog *log in gpSuccessArr) {
                [logs removeObject:log];
            }
            order.orderLogs = logs;
            _order = order;
            [self configuration];
        } else {
            [self showHint:@"获取订单详情失败!"];
        }
    }];
}

- (void)configuration
{
    switch (_order.status) {
        case ZDOrderStatusRush:
        case ZDOrderStatusWait:
            self.calcleOrderButton.hidden = NO;
            break;
        default:
            self.calcleOrderButton.hidden = YES;
            break;
    }
    
    switch (_order.status) {
        case ZDOrderStatusWait:
        case ZDOrderStatusDoing:
        case ZDOrderStatusEnded:
        case ZDOrderStatusCancel:
        case ZDOrderStatusOffset:
            self.bottomConstraint.priority = 800;
            self.addPriceButton.hidden = YES;
            break;
        default:
            break;
    }
    
    [self.orderNumberButton setTitle:_order.orderNum forState:UIControlStateNormal];
    self.orderStatusLabel.text = _order.orderTitle;
    self.orderStatusLabel.textColor = _order.orderColor;
    self.orderPriceLabel.text = [NSString stringWithFormat:@"￥%.2f", _order.sumPrice];
    self.timeLabel.text = _order.appointmentTime;
    self.amountLabel.text = [NSString stringWithFormat:@"%.1f方", _order.volume];
    self.cartypeLabel.text = [_order.style1 stringByAppendingFormat:@"（%ld辆）", _order.count];
    self.conditionLabel.text = [_order.conditionName stringByAppendingString:@"："];
    self.distanceLabel.text = _order.condition;
    self.nameLabel.text = _order.stationName;
    if ([BMUtils isEmptyString:_order.disName]) {
        self.personLabel.text = [@"" stringByAppendingFormat:@"（%@）", _order.disPhone];
    } else {
        self.personLabel.text = [_order.disName stringByAppendingFormat:@"（%@）", _order.disPhone];
    }
    self.remarkLabel.text = [BMUtils isEmptyString:_order.remarks] ? @"无" : _order.remarks;
    [self.remarkLabel sizeToFit];
    UIView *headerView = self.tableView.tableHeaderView;
    CGRect frame = headerView.frame;
    frame.size.height = CGRectGetMaxY(_remarkLabel.frame) + 10.f;
    headerView.frame = frame;
    [self.tableView setTableHeaderView:headerView];
    
    double singlePrice = _order.sumPrice / _order.volume;
    
    self.singleLabel.text = [NSString stringWithFormat:@"%.1f元/方", singlePrice];
    
    [self.tableView reloadData];
}

- (CAlertView *)alertView
{
    if (!_alertView) {
        _alertView = [[CAlertView alloc] initWithView:[[NSBundle mainBundle] loadNibNamed:@"OrderDetailView" owner:self options:nil].firstObject];
    }
    return _alertView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_order.status <= ZDOrderStatusDoing || _order.status == ZDOrderStatusOffset) {
        NSUInteger count = _order.orderLogs.count;
        if (count) {
            return count;
        } else {
            return 1;
        }
    } else {
        return _order.orderLogs.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = _order.orderLogs.count;
    if (count) {
        ZDOrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
        cell.log = _order.orderLogs[indexPath.row];
        
        cell.workStatusLabel.text = [cell.log getMsg];
        if (_order.status == ZDOrderStatusDoing || _order.status == ZDOrderStatusEnded) {
            cell.workStatusLabel.hidden = NO;
            if (cell.log.damage <= 0)
                cell.workStatusLabel.text = [cell.log getMsg];
            else
                cell.workStatusLabel.text = [NSString stringWithFormat:@"%@(获赔%.1f元)", [cell.log getMsg], cell.log.damage];
        } else if (_order.status == ZDOrderStatusCancel) {
            if (cell.log.statusId == 5 || cell.log.statusId == 11 || cell.log.statusId == 12) {
                //                cell.workStatusLabel.hidden = YES;
            } else {
                cell.workStatusLabel.hidden = NO;
                cell.workStatusLabel.text = [NSString stringWithFormat:@"获赔%.1f元", cell.log.damage];
            }
        } else {
            if (cell.log.statusId == ZDOwnerStatusGP) {
                cell.workStatusLabel.hidden = NO;
                cell.workStatusLabel.text = [cell.log getMsg];
            } else {
                //                cell.workStatusLabel.hidden = YES;
            }
        }
        return cell;
    } else {
        ZDEmptyWorkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"emptyCell" forIndexPath:indexPath];
        // FIXME 如果订单开始时间大于当前时间，提示超时。
        NSDate *currentDate = [NSDate new];
        NSDateFormatter *formatter = [NSDateFormatter new];
        formatter.dateFormat = @"yyyy-MM-dd HH-mm";
        NSDate *date = [formatter dateFromString:_order.name];
        BOOL early = [date isEarlierThanDate:currentDate];
        if (early || _order.status == ZDOrderStatusOffset) {
            [cell.statusButton setTitle:@"该订单已超时，无司机接单。" forState:UIControlStateNormal];
        }
        cell.userInteractionEnabled = NO;
        
        if (_order.status != ZDOrderStatusOffset) {
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
            animation.delegate = self;
            animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI , 0, 0, 1.0)];
            animation.duration = 1;
            animation.cumulative = YES;
            animation.repeatCount = INT_MAX;
            //        animation.speed = 10;
            [cell.statusButton.imageView.layer addAnimation:animation forKey:@"animation"];
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_order.status == ZDOrderStatusCancel) {
        return;
    }
    ZDWorkDetailController *workVC = [ZDWorkDetailController new];
    workVC.log = _order.orderLogs[indexPath.row];
    workVC.order = _order;
    [self showViewController:workVC sender:nil];
}

- (IBAction)cancleOrderAction:(id)sender {
    if (_order.orderLogs.count) {
        [self cancleMsg];
    } else {
        NSString *msg = @"该订单暂无抢单，取消订单后不会有任何惩罚，确定取消？";
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancleAction];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self cancleOrderTask];
        }];
        [alertVC addAction:okAction];
        //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (IBAction)addPriceAction:(id)sender {
    [self.alertView show];
    self.alertPriceTextfield.text = _order.changeUnitPrice;
}

- (IBAction)alertAction:(UIButton *)sender {
    int price = [_alertPriceTextfield.text intValue];
    switch (sender.tag) {
        case 0:
            [self.alertView dismissAlertViewWithAnimated:YES];
            break;
        case 1:
            [self AddSinglePrice];
            break;
        case 2:
            if (price) {
                price--;
                self.alertPriceTextfield.text = [NSString stringWithFormat:@"%u", price];
            }
            break;
        case 3:
            price++;
            self.alertPriceTextfield.text = [NSString stringWithFormat:@"%u", price];
            break;
    }
}

- (void)AddSinglePrice
{
    [self.alertView dismissAlertViewWithAnimated:YES];
    int price = [_alertPriceTextfield.text intValue];
    NSString *msg = @"";
    if (price > [_order.changeUnitPrice doubleValue]) {
        msg = [NSString stringWithFormat:@"单价调整为%.2f元，订单总额增加%.2f元", _order.unitPrice + price, price * _order.volume];
    } else {
        msg = [NSString stringWithFormat:@"单价调整为%.2f元，订单总额减少%.2f元", _order.unitPrice + price, price * _order.volume];
    }
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:cancleAction];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self addPriceTask];
    }];
    [alertVC addAction:okAction];
    //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
    //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
    [self presentViewController:alertVC animated:YES completion:nil];
}

/**
 *  加价
 */
- (void)addPriceTask
{
    BMRequest *request = [BMRequest requestWithPath:@"increateOrderPrice.htm"];
    request.params = @{@"orderId": @(_order.ID), @"amount": self.alertPriceTextfield.text};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self getData];
        } else {
            [self showHint:@"加价失败!"];
        }
    }];
}

- (void)cancleMsg
{
    BMRequest *request = [BMRequest requestWithPath:@"warnToCancleOrderByDispatcher.htm"];
    request.params = @{@"orderId": @(_order.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"当前时间距离用车时间还有%@,撤销订单将会扣除%.2f元罚金", response.rawResult[@"hourdff"], [response.rawResult[@"fine"] doubleValue]] preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self cancleOrderTask];
            }]];
            [self presentViewController:alertVC animated:YES completion:nil];
        } else {
            [self showHint:response.msg];
        }
    }];
}

/**
 * 撤销订单
 */
- (void)cancleOrderTask
{
    [self showHudWithhint:kDefaultMessage];
    [self.manager cancleOrderByDispatcher:_order complete:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self showHint:@"撤销成功"];
            [self getData];
        } else {
            [self showHint:@"撤销失败"];
        }
    }];
}

- (void)refreshOrder
{
    [self getData];
}

@end
